<template>
    <div class="proj4Btns">
        <a-button type="primary" @click="changeProj4('EPSG3857')">默认坐标系3857</a-button>
        <a-button type="primary" @click="changeProj4('EPSG4490')" style="margin: 0 10px;">自定义坐标系4490</a-button>
        <a-button type="primary" @click="changeProj4('EPSG4326')">地理坐标系4326</a-button>
    </div>
    <div id="map"></div>
</template>

<script setup>
import Map from 'ol/Map'
import View from 'ol/View'
import TileLayer from 'ol/layer/Tile'
import XYZ from 'ol/source/XYZ'
import { defaults } from 'ol/control'
import { register } from 'ol/proj/proj4'
import proj4 from 'proj4'
import { Projection } from 'ol/proj'
import {transform} from 'ol/proj';

const target = 'map'

const layers = [
    new TileLayer({
        source: new XYZ({
            url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
            attributions: '高德地图',
            crossOrigin: 'anonymous',
        })
    })
]

const view = new View({
    // 南京
    center: [118.796877, 32.060255],
    zoom: 10,
    projection: 'EPSG:4326',
})

const createEPSG4326 = () => {
    return  new Projection({
        code: "EPSG:4326",
        unit: "degree",
    })
}

const createEPSG4490 = () => {
    proj4.defs("EPSG:4490","+proj=longlat +ellps=GRS80 +no_defs +type=crs");
    register(proj4);
    return new Projection({
        code: "EPSG:4490",
        unit: "degree",
        // extent: [73.0, 18.0, 135.0, 53.0],
    })
}

const createEPSG3857 = () => {
    proj4.defs("EPSG:3857","+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext  +no_defs");
    register(proj4);
    return new Projection({
        code: "EPSG:3857",
        unit: "m",
        // extent: [-20037508.3427892, -20037508.3427892, 20037508.3427892, 20037508.3427892],
    })
}

const projMap = {
    EPSG4326: createEPSG4326,
    EPSG4490: createEPSG4490,
    EPSG3857: createEPSG3857,

}

const changeProj4 = (proj) => {
    const projection = projMap[proj]()
    view.setProjection(projection)
}

onMounted(() => {
	new Map({
		target: target,
		layers: layers,
		view: view
	})
})
</script>

<style scoped>
.proj4Btns {
    position: absolute;
    top: 0;
    left: 50px;
    z-index: 999;
}
</style>